package cn.edu.zstu.qingzhu.qingzhushop.handler.mybatisplus;

import cn.edu.zstu.qingzhu.qingzhushop.entity.AuthenticationUser;
import cn.edu.zstu.qingzhu.qingzhushop.service.IUserService;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-11-26 15:52
 */
@Slf4j
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private AuthenticationTrustResolver authenticationTrustResolver;
    @Autowired
    private IUserService iUserService;

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("come to insert fill .........");
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authenticationTrustResolver.isAnonymous(authentication) && authentication != null) {
            AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
            this.setFieldValByName("createUser", user.getUsername(), metaObject);
            this.setFieldValByName("updateUser", user.getUsername(), metaObject);
        } else {
            this.setFieldValByName("createUser", "unknown", metaObject);
            this.setFieldValByName("updateUser", "unknown", metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("come to update fill .........");
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!authenticationTrustResolver.isAnonymous(authentication) && authentication != null) {
            AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
            this.setFieldValByName("updateUser", user.getUsername(), metaObject);
        } else {
            this.setFieldValByName("updateUser", "unknown", metaObject);
        }
    }
}
